package com.example.demo.OtherCoding;


import org.apache.tomcat.util.buf.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

public class TestDemo5 {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < 30; i++) {  // 往ArrayList里面塞入30个元素
            list.add(i);
        }
        System.out.println("Original size:" + list.size() + " Original capacity:" + getArrayListCapacity(list));
        for (int i = 0; i < 20; i++) {  // 从列表末尾依次删除20个元素
            list.remove(list.size() - 1);
            System.out.println("Size:" + list.size() + " Capacity:" + getArrayListCapacity(list));
        }
    }
    // ArrayList不能直接返回容量，我们通过反射获得
    private static int getArrayListCapacity(ArrayList<?> arrayList) {
        Class<ArrayList> arrayListClass = ArrayList.class;
        try {
            // 获取elementData字段
            Field field = arrayListClass.getDeclaredField("elementData");
            field.setAccessible(true);  // 开启访问权限
            // 通过反射获取elementData字段的值
            Object[] objects = (Object[]) field.get(arrayList);
            return objects.length;
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            return -1;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return -1;
        }
    }
}